import React,{useState,useEffect} from 'react'
import { Form, Card, Input, Button, message } from 'antd'
import {creatApi,getOneById,modifyOne} from "../../../services/product"

function Add(props) {
  const { getFieldDecorator } = props.form;
  const [currentData,setCurrentData]=useState({});
  // console.log(currentData)
  console.log(props.match.params.id)
  useEffect(()=>{
    if(props.match.params.id){
      getOneById(props.match.params.id).then(res=>{
        console.log(res.data)
        setCurrentData(res.data[0])
      })
  
    }
  },[])
  
  const priceValidate=(rule,value,callback)=>{
    if(value*1>1500){
      callback("价格不能超过1500")
    }else{
      callback()
    }
  }
  const handleSubmit = e => {
    e.preventDefault()
    // 验证
    props.form.validateFields((err, values) => {
      if (!err) {
        // console.log(values)
        // console.log(props.match.params.id)
        //此处写接口
        if(props.match.params.id){
          
          modifyOne(props.match.params.id,values.name,values.num,values.price).then(
            res=>{
              console.log(res.data)
              if(res.data==="success"){
                props.history.push('/admin/product')
              }
            })  

        }else{
          creatApi(values.name,values.num,values.price).then(res=>{
            console.log(res.data)
            if(res.data==="success"){
              props.history.push('/admin/product')
            }
          })  
        }
       

      }
      else {
        message.error("请输入正确的内容")
      }
    });
  };
  return (

    <Card title="商品编辑">
      <Form onSubmit={(e) => handleSubmit(e)}>
        <Form.Item label="名字">
          {getFieldDecorator('name', {
            rules: [{
              required: true, message: "请输入商品名字"
            }],
            initialValue:currentData.name
          })(<Input placeholder="请输入商品名字" />,
          )}

        </Form.Item>

        <Form.Item label="价格">
          {getFieldDecorator('price', {
            rules: [
              {
                required: true,
                message: "请输入商品价格"
              },
              {
                validator:priceValidate
               }
          ],
          initialValue:currentData.price
          })(<Input placeholder="请输入商品价格" />,
          )}
        </Form.Item>

        <Form.Item label="数量">
          {getFieldDecorator('num', {
            rules: [
              {
                required: true,
                message: "请输入商品数量"
              }],
              
          initialValue:currentData.num
          })(<Input placeholder="请输入商品数量" />,
          )}
        </Form.Item>
        <Form.Item>
          <Button htmlType="submit" type="primary">保存</Button>
        </Form.Item>
      </Form>
    </Card>

  )
}

export default Form.create({ name: "productForm" })(Add)
